#!/usr/bin/perl -I./lib
# 
# CGI-BIN script to show a webform with fields filled in
#
# Parameters: key=Key (number-random) of user.
#             db=DBFile
#             form=Formfile
#
use Counter;
use Counter::CGI;
use HTML::TreeBuilder;
use FillForm;

$] > 5.008 && binmode(STDOUT, ":utf8"); # set web page output to utf-8
$entry = new Counter::CGI;

$filename = $entry->param(db);

eval '$file = FileTable::open($filename)';
if ($@) {
    dieform($@);
}

$key = $entry->param(key);
if (!$key) {
    dieform("You have to specify a key");
}

($index, $secret) = split("-", $key);

$record = $file->get($index);
if (!defined($record)) {
    dieform("Record not found for $index");
}
$file = $entry->param(form);

print STDERR "Filling in form $file with data from $file $index\n";
# Manipulate in a few more things - to make them available at need
$record->{_key} = $record->key();
$record->{_file} = $filename;

$doc = FillForm::fillform($record, $file);
	      
print <<EoF;
Content-type: text/html; charset="utf-8"

EoF

# the behaviour of HTML::Entity changed at some point to encode all hi-bytes.
# this matters because this script doesn't know it's dealing with Unicode data
# pull it back to only encoding the Really Important Stuff.
print $doc->as_HTML("'<>&'");



sub dieform {

    my $msg = shift;

    print <<EoF;
content-type: text/html; charset="utf-8"

<html>
<head>
<title>Error message</title>
</head>
<body>
<h1>Error</h1>
Your request could not be completed.
<p>
Reason: $msg
<p>
<!-- appropriate BACK buttons go here -->
</body>
EoF
    die "Error $msg\n";
}

